package com.inspur.edp.bef.builtincomponents.auth;

import com.inspur.edp.bef.core.action.authorityinfo.BefAuthorityInfo;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import io.iec.edp.caf.securityentry.api.data.PermissionEntity;
import io.iec.edp.caf.securityentry.api.data.SecurityEntry;
import io.iec.edp.caf.securityentry.api.manager.SecurityEntryService;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ErpStyleDataPermissionCache implements com.inspur.edp.bef.spi.auth.DataPermissionCache {
  public SecurityEntry authSecurityEntry;
  // 缓存SecurityEntry
  public boolean cachedState;
  @Override
  public void clear() {
    entryActionPermissionMap = null;
    cachedState = false;
    authSecurityEntry = null;
    authorityInfos.clear();
  }

  private Map<String, BefAuthorityInfo> authorityInfos=new HashMap<>();

  public Map<String, BefAuthorityInfo> getAuthorityInfos() {
    return authorityInfos;
  }

  public boolean hasValues(String actionCode,String[] values) {
    if(getAuthorityInfos().containsKey(actionCode))
      return getAuthorityInfos().get(actionCode).hasValues(values);
    return false;
  }

  public void addAuthorityInfos(String actionCode,String[] values) {
    if(authorityInfos.containsKey(actionCode)==false) {
      BefAuthorityInfo info= new BefAuthorityInfo(actionCode);
      info.addList(values);
      authorityInfos.put(actionCode, info);
    }
    else
    {
      BefAuthorityInfo befAuthorityInfo=authorityInfos.get(actionCode);
      befAuthorityInfo.addList(values);
    }
  }

  private ConcurrentHashMap<SecurityEntry, ConcurrentHashMap<String, PermissionEntity>> entryActionPermissionMap;

  /**
   * 根据 SecurityEntry获取 PermissionEntity
   * @param securityEntry
   * @param actionCode
   * @return
   */
  public PermissionEntity getPermissionEntityByCache(SecurityEntry securityEntry, String actionCode) {
    if(this.entryActionPermissionMap == null) {
      this.entryActionPermissionMap = new ConcurrentHashMap<>();
    }
    ConcurrentHashMap<String, PermissionEntity> permissionEntityMap = this.entryActionPermissionMap.get(securityEntry);
    if(permissionEntityMap == null) {
      permissionEntityMap = new ConcurrentHashMap<>();
    }
    PermissionEntity permissionRez = permissionEntityMap.get(actionCode);
    if(permissionRez == null) {
      SecurityEntryService service = SpringBeanUtils.getBean(SecurityEntryService.class);
      permissionRez = service.getPermission(securityEntry,actionCode);
      // 对 permissionRez 进行缓存
      permissionEntityMap.put(actionCode,permissionRez);
      this.entryActionPermissionMap.put(securityEntry, permissionEntityMap);
//			cacheSecurityEntryAndPermissionEntity(securityEntry,actionCode,permissionRez);
    }
    return permissionRez;
  }
}
